package com.bodgittandscarper.brokerhmi;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import static java.util.logging.Level.*;
import java.util.logging.Logger;

import javax.swing.SwingUtilities;

import com.bodgittandscarper.broker.server.Server;
import com.bodgittandscarper.broker.types.ModeFlag;
import com.bodgittandscarper.brokerhmi.control.BASControl;
import com.bodgittandscarper.brokerhmi.model.HMIModel;
import com.bodgittandscarper.brokerhmi.view.HMIMainView;

/**
 * Control class for GUI part of Application. The GUI application is designed with a Model-View-Control design pattern 
 * approach.
 * First the control part is initialized, handling the access(networked or nonnetworked mode) to the client-side of the 
 * Server application. This is done in the {@link com.bodgittandscarper.brokerhmi.control.BASControl}
 * When the access to the database is successfully established, the model and view is initialized.
 *   
 * 
 * @author Morten Rummelhoff
 *
 */
public class BrokerHMI {

	private Logger log = Logger.getLogger(getClass().getName());

	private BASControl basControl;
	
	/**
	 * Constructor for GUI class. ModeFlag and Server are required arguments for initializing the GUI. 
	 * The GUI exits(<code>System.exit(-1)</code>) if a RMI exception (<code>RemoteException</code> or 
	 * <code>NotBoundException</code>) is thrown
	 * 
	 * @param mode Specifies the mode of the GUI.
	 * @param server Argument only needed if Application is started in alone mode. In alone mode, the GUI communicates with the 
	 * <code>Server</code> from the <code>BrokerClient</code> in a non-networked mode. A reference to the BrokerClient is 
	 * made accessible from the <code>Server</code> class.
	 * 
	 */
	public BrokerHMI(ModeFlag mode, Server server) {
		if (log.isLoggable(INFO))
			log.log(INFO, "Starting BrokerHMI in mode: " + mode);
		
		//Create hmimodel
		final HMIModel hmiModel = new HMIModel();
		
		try {
			basControl = new BASControl(mode, hmiModel, server);
		} catch (RemoteException e) {
			if (log.isLoggable(SEVERE))
				log.log(SEVERE, "Unable to Start HMI", e);
			System.exit(-1);
			
		} catch (NotBoundException e) {
			if (log.isLoggable(SEVERE))
				log.log(SEVERE, "Unable to Start HMI", e);
			System.exit(-1);
		} 
		
		//initialization of the GUI is done in EDT.
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				//Create GUI with control
				new HMIMainView(hmiModel, basControl);
						
			}
		});
		
		
	}
	
}
